package services;

import java.util.Collection;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import repositories.GalleryRepository;
import domain.Customer;
import domain.Gallery;

@Service
@Transactional
public class GalleryService {

	// Managed repository

	@Autowired
	private GalleryRepository galleryRepository;

	// Supporting services
	
	@Autowired
	private ActorService actorService;
	
	// Simple CRUD methods

	public Gallery create() {
		Gallery gallery = new Gallery();
		Customer customer = (Customer) actorService.findByPrincipal();
		gallery.setCustomer(customer);
		return gallery;
	}
	
	public void save(Gallery gallery){
		checkPrincipal(gallery);
		Assert.notNull(gallery);
		galleryRepository.save(gallery);
	}
	
	public void delete(Gallery gallery){
		checkPrincipal(gallery);
		Assert.notNull(gallery);
		Assert.isTrue(gallery.getId() != 0);
		Assert.isTrue(galleryRepository.exists(gallery.getId()));
		Assert.isTrue(gallery.getPaintings().isEmpty(),"gallery.commit.error.paintings");
		
		galleryRepository.delete(gallery);
	}
	
	// Other business methods
	
	public void checkPrincipal(Gallery gallery){
		Assert.notNull(gallery);
		Customer principal = (Customer) actorService.findByPrincipal();
		Assert.isTrue(gallery.getCustomer().equals(principal), "gallery.delete.error.notPrincipal");
	}
	
	public Gallery findOne (int galleryId){
		return galleryRepository.findOne(galleryId);
	}

	public Collection<Gallery> findGalleriesByCustomerId(int customerId){
		return galleryRepository.findGalleriesByCustomerId(customerId);
	}
	
	public Collection<Gallery> findGalleriesByPrincipal(){
		Customer principal = (Customer) actorService.findByPrincipal();
		return galleryRepository.findGalleriesByCustomerId(principal.getId());
	}
	
	public Collection<Gallery> findMostExpensiveGallery(){
		return galleryRepository.findMostExpensiveGallery();
	}
	
}
